#include "texture.h"

/*
 * Texture: Constructor.
 */
Texture::Texture(){
	m_Texture=0;
	m_bLoaded=false;
	m_iWidth=0;
	m_iHeight=0;
}

/*
 * ~Texture: Consturctor
 */
Texture::~Texture()
{
}

/*
 * init: Load image from a filename with a format.
 * @_filename Image name
 * @_FileFormat Texture image format
 * @return bool true if load goes OK
 */   
bool Texture::init(const char *_filename){
  
	SDL_Surface *texAux; 
	GLenum textureFormat;
	m_pLog=&Log::getInstance();

	if (!(texAux=IMG_Load(_filename)))
	{
		m_pLog->error("Unable to load [%s]",_filename); 
		return false;
	}

	glGenTextures( 1, &m_Texture );  
	glBindTexture( GL_TEXTURE_2D, m_Texture );

  
  /* Set the color mode */
	switch (texAux->format->BytesPerPixel)
	{
  		case 3:
      		if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
        		textureFormat = GL_BGR;
      		else
        		textureFormat = GL_RGB;
    		break;
    	case 4:
      		if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
        		textureFormat = GL_BGRA;
      		else
        		textureFormat = GL_RGBA;    
		break;
  	}

  /* Genarate texture */
  	glGenTextures(1, &m_Texture);
  	glBindTexture(GL_TEXTURE_2D, m_Texture);
  //~ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  //~ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  	glTexImage2D(GL_TEXTURE_2D, 0, texAux->format->BytesPerPixel, texAux->w,
  	texAux->h, 0, textureFormat, GL_UNSIGNED_BYTE, texAux->pixels);
  
  	glBindTexture( GL_TEXTURE_2D, 0 );

  	m_iWidth=texAux->w;
  	m_iHeight=texAux->h;
  
  	if ( texAux ){
    	SDL_FreeSurface( texAux );
  	}
      
	(void)strcpy(m_filename,_filename);
	m_pLog->debug("+ [%s]",m_filename);   

  	m_bLoaded=true;
  	return true;
}


/*
 * 
 * name: bind
 * Binds image to use.
 * @param N/A
 * @return void
 */
void Texture::bind()
{
  	glBindTexture( GL_TEXTURE_2D, m_Texture );
}

/*
 * 
 * name: freeMemory
 * Free memory of image.
 * @param N/A
 * @return void
 */
void Texture::freeMemory()
{
	glBindTexture( GL_TEXTURE_2D, 0 );

    if(m_bLoaded)
	{
	  	glDeleteTextures(1,&m_Texture);
	}
	m_bLoaded=false;  
  
  	//~ delete m_filename;
  	m_pLog->debug("- Texture");    
  	m_pLog=0;
}
